const express = require('express')
const router = express.Router()
const db = require('../db/db.js')
const confirmToken = require('../middlewares/confirmToken')

// 新增学生信息
router.post('/api/student', confirmToken, (req, res) => {
    const student = {
        number: req.body.number,
        class: req.body.class,
        name: req.body.name,
        sex: req.body.sex,
        mysql: req.body.mysql,
        web: req.body.web,
        vue: req.body.vue
    }
    new db.Student(student).save()
    res.status(200).send('succeed in saving new passage.')
})

// 查询所有学生信息 可分页
router.get('/api/students', (req, res) => {
    const page = req.query.pagenum
    const name = req.query.name
    const number = req.query.number
    const limit = req.query.pagesize - 0 || 100
    const skip = limit * (page - 1)
    if (name !== '' || number !== '') {
        const nameRe = new RegExp(name, 'i')
        const numberRe = new RegExp(number, 'i')
        db.Student.find({ name: nameRe, number: numberRe}).limit(limit).skip(skip).exec()
            .then((students1) => {
                let total = 0
                db.Student.find({ name: nameRe, number: numberRe}).exec().then((students2) => {
                    total = students2.length
                    res.send({students: students1, total: total})
                })
            })
    } else {
        db.Student.find().sort().limit(limit).skip(skip).exec().then((students1) => {
            let total = 0
            db.Student.find().exec().then((students2) => {
                total = students2.length
                res.send({students: students1, total: total})
            })
        })
    }
})


// 获取某个学生信息
router.get('/api/student/:sid', (req, res) => {
    db.Student.findOne({ _id: req.params.sid }, (err, doc) => {
        if (err) {
            console.log(err)
        } else {
            res.status(200).send(doc)
        }
    })
})


// 更新学生信息
router.post('/api/student/:sid', confirmToken, (req, res) => {
    const sid = req.params.sid
    const student = {
        number: req.body.number,
        class: req.body.class,
        name: req.body.name,
        sex: req.body.sex,
        mysql: req.body.mysql,
        web: req.body.web,
        vue: req.body.vue
    }
    db.Student.update({ _id: sid }, student, (err, data) => {
        if (err) {
            console.log(err)
        } else {
            res.status(200).send({
                _id: sid
            })
        }
    })
})

// 删除某个学生信息
router.delete('/api/student/:sid', confirmToken, (req, res) => {
    const sid = req.params.sid
    db.Student.remove({ _id: sid }, (err, data) => {
        if (err) {
            console.log(err)
        } else {
            res.status(200).send({
                _id: sid
            })
        }
    })
})

module.exports = router
